package com.zzx.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzx.entity.TTest;
import com.zzx.mapper.TTestMapper;
import com.zzx.service.TTestService;
import com.zzx.config.UserContext;
import com.zzx.utils.PageUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.List;

/**
 * @author zzx
 * @description 针对表【t_test(测试)】的数据库操作Service实现
 * @createDate 2025-06-14
 */
@Service
public class TTestServiceImpl extends ServiceImpl<TTestMapper, TTest>
        implements TTestService {


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(TTest param) {
        LambdaQueryWrapper<TTest> wrapper = new LambdaQueryWrapper<>(TTest.class);
        wrapper.eq(TTest::getCompanyId, UserContext.getCompanyId());
        wrapper.eq(TTest::getTestName, param.getTestName());

        if (ObjectUtils.isEmpty(param.getTestId())) {
            param.setTestId(IdUtil.getSnowflakeNextId());
        } else {
            wrapper.ne(TTest::getTestId, param.getTestId());
            TTest dbEntity = this.getBaseMapper().selectById(param.getTestId());
            if (dbEntity != null) {
                BeanUtil.copyProperties(dbEntity, param);
            }
        }

        List<TTest> existList = this.getBaseMapper().selectList(wrapper);
        if (!existList.isEmpty()) {
            throw new RuntimeException("名称重复");
        }

        this.saveOrUpdate(param);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteById(TTest param) {
        this.removeById(param.getTestId());
    }

    @Override
    public IPage<TTest> selectBy(TTest param) {
        LambdaQueryWrapper<TTest> wrapper = new LambdaQueryWrapper<>(TTest.class);

        if (!ObjectUtils.isEmpty(param.getTestName())) {
            wrapper.like(TTest::getTestName, param.getTestName());
        }
        if (!ObjectUtils.isEmpty(param.getTestCode())) {
            wrapper.like(TTest::getTestCode, param.getTestCode());
        }
        if (!ObjectUtils.isEmpty(param.getTestId())) {
            wrapper.eq(TTest::getTestId, param.getTestId());
        }

        wrapper.eq(TTest::getCompanyId, UserContext.getCompanyId());
        wrapper.orderByDesc(TTest::getCreateTime);

        return this.getBaseMapper().selectPage(
                PageUtils.createPage(param.getPageNum(), param.getPageSize()),
                wrapper
        );
    }

    @Override
    public TTest findById(String id) {
        return this.getBaseMapper().selectById(id);
    }
}
